﻿<!DOCTYPE html>
<html>
	<meta charset="UTF-8"/>
	<head>
		<script>
			var list = [1,5,6,8,23,90,12];
			list.sort(function(a,b){
				return a-b;
			});
			
			//console.log(list);
			
			//冒泡排序
			var a = [12,9,999,1,2,3,38,44,98,7,35,59,49,88,100,38];
			/*
			for(var i=0; i<a.length-1; i++){
				for(var j=0; j<a.length-i-1; j++){
					if(a[j] > a[j+1]) {
						var temp = a[j];
						a[j] = a[j+1];
						a[j+1] = temp;
					}
				}
			} 
			console.log(a);
			*/
			
			/*
			//选择排序
			for(var i=0; i<a.length-1; i++){
				for(var j=i+1; j<a.length; j++){
					if(a[i] > a[j]){
						var temp = a[i];
						a[i] = a[j];
						a[j] = temp;
					}
				}
			}
			console.log(a);
			*/
			
			//快速排序
			function quicksort(arr){
				//当长度为1或0时，停止递归，直接返回
				if(arr.length < 2) return arr;
				//计算中间元素的下标
				var midIndex = arr.length%2==0 ? arr.length/2 : (arr.length-1)/2;
				//获取中间元素
				var midVal = arr[midIndex];
				
				var left = [],right = [];
				//遍历数组，将小的放左边，大的放右边
				for(var i in arr){
					if(i == midIndex) continue; //忽略中间元素
					arr[i]<=midVal ? left.push(arr[i]) : right.push(arr[i]);
				}
				//左右两边分别再次递归
				return quicksort(left).concat(midVal).concat(quicksort(right));
			}
			
			console.log( quicksort(a) );
			
		</script>
	</head>
	<body>
		
	
	</body>	
</html>











